<?php

class Api extends Front_Controller {

    function __construct()
    {
        parent::__construct();
        //make sure we're not always behind ssl
        remove_ssl();
        header('Content-Type: application/json');
    }

    function index()
    {
        $this->load->helper('directory');
        $data['json'] ='hello world';
        $this->load->view('api', $data);
    }

    function category($id='0')
    {
        //get the category
        $data['category']			= $this->Category_model->get_category($id);
        if ($id =='0')
        {
            $data['categories']		= $this->Category_model->get_categories('0');
            $data['json'] = $data['categories'];
            $this->load->view('api', $data);
        }

        else
        {
            if (!$data['category'])
            {
                show_404();
            }
            //set up pagination
            $segments	= $this->uri->total_segments();
            $base_url	= $this->uri->segment_array();
            if($data['category']->slug == $base_url[count($base_url)])
            {
                $page	= 0;
                $segments++;
            }
            else
            {
                $page	= array_splice($base_url, -1, 1);
                $page	= $page[0];
            }
            $data['subcategories']		= $this->Category_model->get_categories($data['category']->id);
            $sort_array = array(
                'name/asc' => array('by' => 'products.name', 'sort'=>'ASC'),
                'name/desc' => array('by' => 'products.name', 'sort'=>'DESC'),
                'price/asc' => array('by' => 'products.price', 'sort'=>'ASC'),
                'price/desc' => array('by' => 'products.price', 'sort'=>'DESC'),
            );
            $sort_by	= array('by'=>'sequence', 'sort'=>'ASC');
            if(isset($_GET['by']))
            {
                if(isset($sort_array[$_GET['by']]))
                {
                    $sort_by	= $sort_array[$_GET['by']];
                }
            }
            //grab the products using the pagination lib
            $data['products']	= $this->Product_model->get_products($data['category']->id, 100, 0, $sort_by['by'], $sort_by['sort']);
            foreach ($data['products'] as &$p)
            {
                $p->images	= (array)json_decode($p->images);
                $p->options	= $this->Option_model->get_product_options($p->id);
            }
            $data['json'] = $data['subcategories'];
            $this->load->view('api', $data);
        }
    }

    function product_list($id)
    {
        //get the category
        $data['category']			= $this->Category_model->get_category($id);
        if (!$data['category'])
        {
            show_404();
        }
        //set up pagination
        $segments	= $this->uri->total_segments();
        $base_url	= $this->uri->segment_array();
        if($data['category']->slug == $base_url[count($base_url)])
        {
            $page	= 0;
            $segments++;
        }
        else
        {
            $page	= array_splice($base_url, -1, 1);
            $page	= $page[0];
        }
        $sort_array = array(
            'name/asc' => array('by' => 'products.name', 'sort'=>'ASC'),
            'name/desc' => array('by' => 'products.name', 'sort'=>'DESC'),
            'price/asc' => array('by' => 'products.price', 'sort'=>'ASC'),
            'price/desc' => array('by' => 'products.price', 'sort'=>'DESC'),
        );
        $sort_by	= array('by'=>'sequence', 'sort'=>'ASC');
        if(isset($_GET['by']))
        {
            if(isset($sort_array[$_GET['by']]))
            {
                $sort_by	= $sort_array[$_GET['by']];
            }
        }
        //grab the products using the pagination lib
        $data['products']	= $this->Product_model->get_products($data['category']->id, 100, 0, $sort_by['by'], $sort_by['sort']);
        foreach ($data['products'] as &$p)
        {
            $p->images	= (array)json_decode($p->images,true);
            $p->images	= array_shift($p->images);
            $p->image = ($p->images['filename']);
            $p->seller="grace".rand(1,5);
            unset ($p->images);
            unset( $p->categories);
            //no need
        }
        $data['json'] = $data['products'];
        $this->load->view('api', $data);
    }

    function product($id)
    {
        //get the product
        $data['product']	= $this->Product_model->get_product($id);
        if(!$data['product'] || $data['product']->enabled==0)
        {
            show_404();
        }
        // load the digital language stuff
        //
        $this->lang->load('digital_product');
        $data['options']	= $this->Option_model->get_product_options($data['product']->id);
        $related			= $data['product']->related_products;
        $data['related']	= array();
        $data['posted_options']	= $this->session->flashdata('option_values');

        $data['page_title']			= $data['product']->name;
        if($data['product']->images == 'false')
        {
            $data['product']->images = array();
        }
        else
        {
            $data['product']->images	= array_values((array)json_decode($data['product']->images));
        }

        $data['json'] = $data;
        $this->load->view('api', $data);
    }

	// This saves the confirmed order 
	function new_order() {

		$this->load->model('order_model');
		$this->load->model('Product_model');

		//prepare our data for being inserted into the database
		$save	= array();
        $customer_id = $this->input->post('customer_id');
    	$product =  $this->input->post('product');

	    $save['status']				= $this->config->item('nonship_status');
		//if the id exists, then add it to the array $save array and remove it from the customer
		if(isset($customer_id) && $customer_id != '')
		{
			$save['customer_id']	= $customer_id;
		}

		$customer					= NULL;  // $this->_cart_contents['customer'];
		$ship						= NULL;  // $customer['ship_address'];
		$bill						= NULL;  // $customer['bill_address'];

		$save['company']			= NULL;  // $customer['company'];
		$save['firstname']			= NULL;  // $customer['firstname']; 
		$save['lastname']			= NULL;  // $customer['lastname'];
		$save['phone']				= NULL;  // $customer['phone'];
		$save['email']				= NULL;  // $customer['email'];

		$save['ship_company']		= NULL;  // $ship['company'];
		$save['ship_firstname']		= NULL;  // $ship['firstname'];
		$save['ship_lastname']		= NULL;  // $ship['lastname'];
		$save['ship_email']			= NULL;  // $ship['email'];
		$save['ship_phone']			= NULL;  // $ship['phone'];
		$save['ship_address1']		= NULL;  // $ship['address1'];
		$save['ship_address2']		= NULL;  // $ship['address2'];
		$save['ship_city']			= NULL;  // $ship['city'];
		$save['ship_zip']			= NULL;  // $ship['zip'];
		$save['ship_zone']			= NULL;  // $ship['zone'];
		$save['ship_zone_id']		= NULL;  // $ship['zone_id'];
		$save['ship_country']		= NULL;  // $ship['country'];
		$save['ship_country_id']	= NULL;  // $ship['country_id'];

		$save['bill_company']		= NULL;  // $bill['company'];
		$save['bill_firstname']		= NULL;  // $bill['firstname'];
		$save['bill_lastname']		= NULL;  // $bill['lastname'];
		$save['bill_email']			= NULL;  // $bill['email'];
		$save['bill_phone']			= NULL;  // $bill['phone'];
		$save['bill_address1']		= NULL;  // $bill['address1'];
		$save['bill_address2']		= NULL;  // $bill['address2'];
		$save['bill_city']			= NULL;  // $bill['city'];
		$save['bill_zip']			= NULL;  // $bill['zip'];
		$save['bill_zone']			= NULL;  // $bill['zone'];
		$save['bill_zone_id']		= NULL;  // $bill['zone_id'];
		$save['bill_country']		= NULL;  // $bill['country'];
		$save['bill_country_id']	= NULL;  // $bill['country_id'];

		//shipping information
		$save['shipping_method']	= 0   ;   // $this->_cart_contents['shipping']['method'];
		$save['shipping']			= 0.00;  // $this->_cart_contents['shipping']['price'];

		//add in the other charges
		$save['tax']				= 0.00; // $this->_cart_contents['tax'];

		//discounts
		$save['gift_card_discount'] = 0.00; // $this->_cart_contents['gift_card_discount'];
		$save['coupon_discount']	= 0.00; // $this->_cart_contents['coupon_discount'];
		$save['subtotal']			= 0 ;// $this->_cart_contents['cart_subtotal'];
		$save['total']				= 0; // $this->_cart_contents['cart_total'];
	    $save['payment_info']	= '';
		//save additional details
		$save['referral']		= 0; //$this->get_additional_detail('referral');
		$save['shipping_notes']	= '  '; //$this->get_additional_detail('shipping_notes');
		//ordered_on datetime stamp
		$save['ordered_on']			= date('Y-m-d H:i:s');	
		//contents this is the content section serialized
		//later on if we want to add out of stock counting here is where we will
		//decrement our stock
		$contents					= array();
		$this->load->model('Product_model');
		foreach ($product as $one_item)
		{
            $moreinfo = (array) $this->Product_model->get_product($one_item['id'],FALSE);
            unset ($moreinfo['categories']);
            $moreinfo['quantity'] = $one_item['quantity'];
            $one_item = $moreinfo;
            $save['subtotal'] += $one_item['saleprice'] * $one_item['quantity'];
			$contents[]				= serialize($one_item);
            print_r ($one_item);
		}
        $save['total'] = $save['subtotal'];
		// save the order content
		$order_id					= $this->order_model->save_order($save, $contents);
		// dont do anything else if the order failed to save
		if(!$order_id) return false;

        echo $order_id;
	}

}
?>
